import React, { useRef, useEffect, useCallback } from 'react';
import { Particle, ConnectionLine } from './types';
import { 
  PARTICLE_SIZE_RANGE,
  MERGE_DISTANCE, 
  MERGE_PROBABILITY,
  MERGE_ANIMATION_DURATION,
  GRAVITY_FACTOR,
  GRAVITY_THRESHOLD,
  BIG_BANG_THRESHOLD,
  CONNECTION_LINE_ALPHA,
  CONNECTION_PULSE_SPEED,
  MIN_PARTICLES,
  MAX_PARTICLES,
  INITIAL_PARTICLES,
  PARTICLE_CREATION_INTERVAL,
  PERFORMANCE_CHECK_INTERVAL,
  ROBOT_INTERACTION_RADIUS
} from './constants';
import { 
  createParticle, 
  getTotalParticleCount, 
  removeRandomParticle, 
  triggerBigBang,
  getRandomColor
} from './utils';

interface ParticleAnimationProps {
  canvas: HTMLCanvasElement;
  ctx: CanvasRenderingContext2D;
  particlesRef: React.MutableRefObject<Particle[]>;
  connectionPulsesRef: React.MutableRefObject<{[key: string]: number}>;
  robotRef: React.MutableRefObject<any>;
  lowPerformanceMode: boolean;
}

// 生成新粒子
export const generateParticles = (
  canvas: HTMLCanvasElement,
  particlesRef: React.MutableRefObject<Particle[]>,
  lastParticleCreationRef: React.MutableRefObject<number>,
  lowPerformanceMode: boolean
): void => {
  // 检查总粒子数
  const currentCount = getTotalParticleCount(particlesRef);
  
  // 如果粒子数低于最小值，创建一些新粒子
  if (currentCount < MIN_PARTICLES) {
    const needToCreate = MIN_PARTICLES - currentCount;
    for (let i = 0; i < needToCreate; i++) {
      createParticle(canvas, particlesRef);
    }
    return;
  }
  
  const now = Date.now();
  
  // 控制运行时粒子数量
  const targetParticles = lowPerformanceMode ? MIN_PARTICLES : (MIN_PARTICLES + 30);
  
  // 在低性能模式下减少粒子生成频率
  const interval = lowPerformanceMode ? PARTICLE_CREATION_INTERVAL * 3 : PARTICLE_CREATION_INTERVAL;
  
  // 只有当粒子数量低于目标数时才生成新粒子
  if (now - lastParticleCreationRef.current > interval && particlesRef.current.length < targetParticles) {
    createParticle(canvas, particlesRef);
    lastParticleCreationRef.current = now;
  }
};

// 更新粒子
export const updateParticles = (
  canvas: HTMLCanvasElement,
  particlesRef: React.MutableRefObject<Particle[]>,
  connectionPulsesRef: React.MutableRefObject<{[key: string]: number}>,
  robotRef: React.MutableRefObject<any>
): ConnectionLine[] => {
  const robot = robotRef.current;
  const mergingParticles = new Set<number>(); // 用于存储正在合并的粒子索引
  const particlesAttractedByGravity = new Set<number>(); // 受重力影响的粒子
  const connectionLines: ConnectionLine[] = [];
  
  // 检查重力吸引
  for (let i = 0; i < particlesRef.current.length; i++) {
    const p1 = particlesRef.current[i];
    if (p1.merging || p1.exploding) continue;
    
    // 清除上一帧的吸引列表
    p1.attractingParticles = p1.attractingParticles || [];
    p1.attractingParticles = [];
    
    // 只有较大的粒子会吸引较小的粒子
    for (let j = 0; j < particlesRef.current.length; j++) {
      if (i === j) continue;
      
      const p2 = particlesRef.current[j];
      if (p2.merging || p2.exploding || particlesAttractedByGravity.has(j)) continue;
      
      // 大粒子吸引小粒子的重力效应
      if (p1.size > p2.size * GRAVITY_THRESHOLD) {
        const dx = p1.x - p2.x;
        const dy = p1.y - p2.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 在一定距离内产生重力效应
        if (distance < p1.size * 10) { // 增加重力作用距离
          // 吸引力与距离成反比，与粒子大小成正比
          const gravityForce = GRAVITY_FACTOR * (p1.size / p2.size) / (distance * 0.1);
          const angle = Math.atan2(dy, dx);
          
          p2.speedX += Math.cos(angle) * gravityForce;
          p2.speedY += Math.sin(angle) * gravityForce;
          
          // 添加到被吸引粒子集合中
          particlesAttractedByGravity.add(j);
          p1.attractingParticles!.push(p2.id);
          
          // 为每条连接线生成唯一ID
          const lineId = `${p1.id}-${p2.id}`;
          
          // 初始化或更新连接线脉冲
          if (!connectionPulsesRef.current[lineId]) {
            connectionPulsesRef.current[lineId] = 0;
          }
          
          // 添加连接线，包含脉冲进度
          const alphaFactor = Math.max(0, 1 - distance / (p1.size * 10));
          connectionLines.push({
            particle1: p1,
            particle2: p2,
            x1: p1.x,
            y1: p1.y,
            x2: p2.x,
            y2: p2.y,
            alpha: CONNECTION_LINE_ALPHA * alphaFactor,
            color: p1.color,
            id: lineId,
            progress: connectionPulsesRef.current[lineId],
            distance: distance,
            strength: (p1.size / p2.size) / (distance * 0.1)
          });
          
          // 更新脉冲进度 (0到1循环)
          connectionPulsesRef.current[lineId] = (connectionPulsesRef.current[lineId] + CONNECTION_PULSE_SPEED / 60) % 1;
        }
      }
    }
  }
  
  // 删除不再使用的脉冲记录
  for (const lineId in connectionPulsesRef.current) {
    let found = false;
    for (const line of connectionLines) {
      if (line.id === lineId) {
        found = true;
        break;
      }
    }
    if (!found) {
      delete connectionPulsesRef.current[lineId];
    }
  }
  
  // 检查粒子的合并
  for (let i = 0; i < particlesRef.current.length; i++) {
    if (mergingParticles.has(i) || particlesRef.current[i].merging || particlesRef.current[i].exploding) continue;
    
    for (let j = i + 1; j < particlesRef.current.length; j++) {
      if (mergingParticles.has(j) || particlesRef.current[j].merging || particlesRef.current[j].exploding) continue;
      
      const p1 = particlesRef.current[i];
      const p2 = particlesRef.current[j];
      
      // 计算两个粒子之间的距离
      const dx = p1.x - p2.x;
      const dy = p1.y - p2.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      // 决定哪个粒子吞并哪个粒子 (大的吞并小的)
      let predator, prey;
      if (p1.size >= p2.size) {
        predator = p1;
        prey = p2;
      } else {
        predator = p2;
        prey = p1;
      }
      
      // 如果粒子足够近，并且满足合并概率，则开始合并
      if (distance < MERGE_DISTANCE && Math.random() < MERGE_PROBABILITY) {
        // 设置合并中心点 (保持在捕食者位置)
        const mergeX = predator.x;
        const mergeY = predator.y;
        
        // 设置合并后的大小
        const mergeSize = Math.min(
          predator.size + prey.size * 0.6,
          PARTICLE_SIZE_RANGE.max * 2.5
        );
        
        // 设置捕食者的合并属性
        predator.merging = true;
        predator.mergePartner = prey.id;
        predator.mergeProgress = 0;
        predator.mergeTargetX = mergeX;
        predator.mergeTargetY = mergeY;
        predator.mergeStartSize = predator.size;
        predator.mergeTargetSize = mergeSize;
        predator.mergeCount = (predator.mergeCount || 0) + (prey.mergeCount || 0) + 1;
        
        // 设置被吞并者的合并属性
        prey.merging = true;
        prey.mergePartner = predator.id;
        prey.mergeProgress = 0;
        prey.mergeTargetX = mergeX;
        prey.mergeTargetY = mergeY;
        prey.mergeStartSize = prey.size;
        prey.mergeTargetSize = 0; // 被吞并的粒子最终会消失
        
        // 将两个粒子标记为正在合并
        mergingParticles.add(i);
        mergingParticles.add(j);
        
        // 让机器人停下来观察合并过程
        const distanceToRobot = Math.sqrt(
          Math.pow(robot.x - mergeX, 2) + 
          Math.pow(robot.y - mergeY, 2)
        );
        
        if (distanceToRobot < ROBOT_INTERACTION_RADIUS * 1.5) {
          robot.observingMerge = true;
          robot.pauseMovement = 60; // 暂停约1秒
          robot.thinking = true;
          robot.thoughtBubbleSize = 0;
        }
        
        break; // 每次只合并一对
      }
    }
  }
  
  // 更新所有粒子
  particlesRef.current = particlesRef.current.filter((particle) => {
    // 增加寿命
    particle.life += 1;
    if (particle.life >= particle.maxLife && !particle.merging && !particle.exploding) return false;
    
    // 处理爆炸中的粒子
    if (particle.exploding) {
      particle.explosionProgress! += 0.02; // 控制爆炸速度
      
      // 更新爆炸碎片
      if (particle.explosionParticles) {
        for (let i = 0; i < particle.explosionParticles.length; i++) {
          const fragment = particle.explosionParticles[i];
          
          // 更新位置
          fragment.x += fragment.speedX;
          fragment.y += fragment.speedY;
          
          // 减小速度 (空气阻力)
          fragment.speedX *= 0.98;
          fragment.speedY *= 0.98;
          
          // 随着爆炸进行逐渐降低不透明度
          fragment.opacity = Math.max(0, fragment.opacity - 0.01);
        }
      }
      
      // 爆炸结束后移除粒子
      if (particle.explosionProgress! >= 1) {
        return false;
      }
    }
    // 处理合并中的粒子
    else if (particle.merging) {
      // 更新合并进度
      particle.mergeProgress! += 1 / (MERGE_ANIMATION_DURATION * 60); // 每帧增加的进度 (60fps)
      
      // 根据合并进度更新位置和大小
      if (particle.mergeProgress! <= 1) {
        // 使用缓动函数使动画更平滑 (二次缓动)
        const t = particle.mergeProgress!;
        const easeT = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
        
        // 平滑移动到目标位置
        particle.x = particle.x + (particle.mergeTargetX! - particle.x) * 0.05;
        particle.y = particle.y + (particle.mergeTargetY! - particle.y) * 0.05;
        
        // 平滑改变大小
        particle.size = particle.mergeStartSize! + (particle.mergeTargetSize! - particle.mergeStartSize!) * easeT;
        
        // 调整不透明度
        if (particle.mergeTargetSize === 0) {
          particle.opacity = particle.opacity * (1 - easeT);
        }
      } else {
        // 合并完成
        if (particle.mergeTargetSize === 0) {
          return false; // 被合并的粒子消失
        } else {
          // 重置合并状态
          particle.merging = false;
          particle.mergePartner = undefined;
          particle.mergeProgress = 0;
          particle.mergeTargetX = undefined;
          particle.mergeTargetY = undefined;
          particle.mergeStartSize = undefined;
          particle.mergeTargetSize = undefined;
          
          // 检查是否达到大爆炸阈值
          if ((particle.mergeCount || 0) >= BIG_BANG_THRESHOLD && !particle.exploding) {
            triggerBigBang(particle, canvas, particlesRef);
          }
        }
      }
    }
    // 非合并状态下的粒子行为
    else {
      // 更新位置
      particle.x += particle.speedX;
      particle.y += particle.speedY;

      // 边界检测
      if (particle.x < 0 || particle.x > canvas.width) {
        particle.speedX *= -0.8;
        particle.x = Math.max(0, Math.min(particle.x, canvas.width));
      }
      if (particle.y < 0 || particle.y > canvas.height) {
        particle.speedY *= -0.8;
        particle.y = Math.max(0, Math.min(particle.y, canvas.height));
      }

      // 透明度基于寿命
      particle.opacity = 0.7 * (1 - particle.life / particle.maxLife);
    }
    
    return true;
  });
  
  return connectionLines; // 返回当前帧的连接线数据
};

// 绘制粒子
export const drawParticles = (
  ctx: CanvasRenderingContext2D,
  particlesRef: React.MutableRefObject<Particle[]>,
  lowPerformanceMode: boolean
): void => {
  particlesRef.current.forEach((particle) => {
    // 处理爆炸效果
    if (particle.exploding) {
      // 在低性能模式下简化爆炸效果
      const explosionScale = lowPerformanceMode ? 5 : (6 + particle.explosionProgress! * 12);
      
      // 绘制爆炸光晕 - 增强光晕效果
      // 提取颜色的rgba值
      let r = 255, g = 255, b = 255;
      
      // 根据颜色格式正确解析RGB值
      if (particle.color.startsWith('#')) {
        // 处理十六进制颜色 #RRGGBB
        const hex = particle.color.slice(1);
        if (hex.length === 6) {
          r = parseInt(hex.slice(0, 2), 16);
          g = parseInt(hex.slice(2, 4), 16);
          b = parseInt(hex.slice(4, 6), 16);
        }
      } else if (particle.color.startsWith('rgb')) {
        // 处理rgb或rgba格式
        const match = particle.color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
        if (match) {
          r = parseInt(match[1], 10);
          g = parseInt(match[2], 10);
          b = parseInt(match[3], 10);
        }
      }
      
      // 创建多层光环，增强渐变效果
      const layers = lowPerformanceMode ? 2 : 4;
      
      for (let i = 0; i < layers; i++) {
        const progress = particle.explosionProgress || 0;
        const layerScale = explosionScale * (1 - i * 0.2);
        
        // 创建光环渐变
        const gradient = ctx.createRadialGradient(
          particle.x, particle.y, 0,
          particle.x, particle.y, particle.size * layerScale
        );
        
        // 设置光环渐变 - 增强中心亮度和渐变过渡
        if (i === 0) {
          // 内层光环 - 明亮的中心
          gradient.addColorStop(0, `rgba(255, 255, 255, ${0.8 - progress * 0.5})`);
          gradient.addColorStop(0.2, `rgba(255, 240, 220, ${0.7 - progress * 0.5})`);
          gradient.addColorStop(0.4, `rgba(${r}, ${g}, ${b}, ${0.6 - progress * 0.4})`);
          gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
        } else {
          // 外层光环 - 更柔和的颜色
          const opacity = 0.5 - i * 0.1 - progress * 0.3;
          gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${opacity})`);
          gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
        }
        
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size * layerScale, 0, Math.PI * 2);
        ctx.fillStyle = gradient;
        ctx.fill();
      }
      
      // 添加脉动波纹环（在非低性能模式下）
      if (!lowPerformanceMode) {
        const waveCount = 3;
        for (let i = 0; i < waveCount; i++) {
          const waveProgress = (particle.explosionProgress! + i / waveCount) % 1;
          const waveRadius = particle.size * (1 + waveProgress * explosionScale * 0.7);
          
          ctx.beginPath();
          ctx.arc(particle.x, particle.y, waveRadius, 0, Math.PI * 2);
          ctx.strokeStyle = `rgba(${r}, ${g}, ${b}, ${0.4 * (1 - waveProgress)})`; 
          ctx.lineWidth = 1.5;
          ctx.stroke();
        }
      }
      
      // 绘制爆炸碎片（在非低性能模式下）
      if (!lowPerformanceMode && particle.explosionParticles) {
        const fragmentsToRender = lowPerformanceMode 
          ? Math.min(15, particle.explosionParticles.length) 
          : particle.explosionParticles.length;
        
        for (let i = 0; i < fragmentsToRender; i++) {
          const fragment = particle.explosionParticles[i];
          
          // 计算当前碎片位置，考虑爆炸进度增加移动距离
          const fragmentX = particle.x + fragment.x * (1 + particle.explosionProgress! * 2);
          const fragmentY = particle.y + fragment.y * (1 + particle.explosionProgress! * 2);
          
          ctx.beginPath();
          ctx.arc(
            fragmentX,
            fragmentY,
            fragment.size * (1 + particle.explosionProgress! * 0.5),
            0, Math.PI * 2
          );
          
          // 使用粒子原本的颜色但调整不透明度
          ctx.fillStyle = particle.color.replace(/[\d.]+\)$/, `${fragment.opacity * (1 - particle.explosionProgress! * 0.5)})`);
          ctx.fill();
          
          // 添加碎片轨迹
          if (!lowPerformanceMode && i % 3 === 0) { 
            const trailGradient = ctx.createLinearGradient(
              particle.x, particle.y,
              fragmentX, fragmentY
            );
            
            trailGradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0)`);
            trailGradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, ${fragment.opacity * 0.4})`);
            
            ctx.beginPath();
            ctx.moveTo(particle.x, particle.y);
            ctx.lineTo(fragmentX, fragmentY);
            ctx.strokeStyle = trailGradient;
            ctx.lineWidth = 1;
            ctx.stroke();
          }
        }
      }
    } 
    // 绘制正常粒子或合并中的粒子
    else {
      ctx.beginPath();
      ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
      
      // 如果是合并中的粒子，添加特殊效果
      if (particle.merging) {
        // 创建合并效果的径向渐变
        const gradient = ctx.createRadialGradient(
          particle.x, particle.y, 0,
          particle.x, particle.y, particle.size * 1.5
        );
        
        // 提取颜色的rgba值
        const baseColor = particle.color.replace(/[^\d,.]/g, '').split(',');
        const r = baseColor[0];
        const g = baseColor[1];
        const b = baseColor[2];
        
        // 设置渐变颜色
        gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 1.2})`);
        gradient.addColorStop(0.6, `rgba(${r}, ${g}, ${b}, ${particle.opacity * 0.7})`);
        gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
        
        ctx.fillStyle = gradient;
      } else {
        ctx.fillStyle = particle.color.replace(/[\d.]+\)$/, `${particle.opacity})`);
      }
      
      ctx.fill();
      
      // 为合并中的粒子添加发光效果
      if (particle.merging && !lowPerformanceMode) {
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size * 1.2, 0, Math.PI * 2);
        ctx.strokeStyle = particle.color.replace(/[\d.]+\)$/, `${particle.opacity * 0.3})`);
        ctx.lineWidth = 2;
        ctx.stroke();
      }
      
      // 为大粒子添加特殊效果
      if (particle.size > PARTICLE_SIZE_RANGE.max * 1.5 && !particle.merging && !lowPerformanceMode) {
        // 添加脉动光晕
        const pulseSize = 1.0 + 0.1 * Math.sin(Date.now() * 0.005);
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size * pulseSize, 0, Math.PI * 2);
        ctx.strokeStyle = particle.color.replace(/[\d.]+\)$/, `${particle.opacity * 0.2})`);
        ctx.lineWidth = 1.5;
        ctx.stroke();
        
        // 显示合并计数
        if (particle.mergeCount && particle.mergeCount > 5) {
          ctx.font = `${Math.min(10, particle.size * 0.5)}px Arial`;
          ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillText(`${particle.mergeCount}`, particle.x, particle.y);
        }
      }
    }
  });
};

// 绘制连接线
export const drawConnectionLines = (
  ctx: CanvasRenderingContext2D,
  connectionLines: ConnectionLine[]
): void => {
  connectionLines.forEach(line => {
    // 计算脉冲位置
    const progress = line.progress || 0;
    
    // 绘制基础线条
    ctx.beginPath();
    ctx.moveTo(line.x1, line.y1);
    ctx.lineTo(line.x2, line.y2);
    
    // 提取基础颜色并调整透明度
    const baseColor = line.color.replace(/[\d.]+\)$/, `${line.alpha * 0.7})`); // 增加基础线透明度
    ctx.strokeStyle = baseColor;
    ctx.lineWidth = 1.5; // 增加线宽
    ctx.stroke();
    
    // 添加脉冲点效果 - 从起点到终点移动的亮点
    const pulseX = line.x1 + (line.x2 - line.x1) * progress;
    const pulseY = line.y1 + (line.y2 - line.y1) * progress;
    
    // 绘制脉冲点
    ctx.beginPath();
    ctx.arc(pulseX, pulseY, 2.5, 0, Math.PI * 2); // 增加脉冲点大小
    const pulseColor = line.color.replace(/[\d.]+\)$/, `${line.alpha * 2.5})`); // 增加脉冲点亮度
    ctx.fillStyle = pulseColor;
    ctx.fill();
    
    // 绘制脉冲尾迹
    const gradient = ctx.createLinearGradient(
      line.x1 + (line.x2 - line.x1) * Math.max(0, progress - 0.2), // 增加尾迹长度
      line.y1 + (line.y2 - line.y1) * Math.max(0, progress - 0.2),
      pulseX,
      pulseY
    );
    
    // 提取RGB部分
    const baseColorParts = line.color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
    if (baseColorParts) {
      const r = baseColorParts[1];
      const g = baseColorParts[2];
      const b = baseColorParts[3];
      
      gradient.addColorStop(0, `rgba(${r}, ${g}, ${b}, 0)`);
      gradient.addColorStop(1, `rgba(${r}, ${g}, ${b}, ${line.alpha * 2.5})`); // 增加尾迹亮度
      
      ctx.beginPath();
      ctx.moveTo(line.x1 + (line.x2 - line.x1) * Math.max(0, progress - 0.2), 
                line.y1 + (line.y2 - line.y1) * Math.max(0, progress - 0.2));
      ctx.lineTo(pulseX, pulseY);
      ctx.strokeStyle = gradient;
      ctx.lineWidth = 3; // 增加尾迹线宽
      ctx.stroke();
    }
  });
};

// 优化性能，简化渲染过程
export function useParticleAnimation() {
  const particlesRef = useRef<Particle[]>([]);
  const connectionPulsesRef = useRef<{[key: string]: number}>({});
  const lastParticleCreationRef = useRef<number>(Date.now());
  const performanceMetricsRef = useRef<{
    lastFrameTime: number;
    frameCount: number;
    fps: number;
    lowPerformanceMode: boolean;
  }>({
    lastFrameTime: performance.now(),
    frameCount: 0,
    fps: 60,
    lowPerformanceMode: false
  });
  const lastPerformanceCheckRef = useRef<number>(performance.now());
  
  // 初始化粒子
  const initParticles = useCallback((canvas: HTMLCanvasElement) => {
    // 生成初始粒子
    for (let i = 0; i < INITIAL_PARTICLES; i++) {
      createParticle(
        canvas,
        particlesRef,
        Math.random() * canvas.width,
        Math.random() * canvas.height,
        PARTICLE_SIZE_RANGE.min + Math.random() * (PARTICLE_SIZE_RANGE.max - PARTICLE_SIZE_RANGE.min)
      );
    }
  }, []);
  
  // 监测性能并动态调整
  const checkPerformance = useCallback((timestamp: number) => {
    const metrics = performanceMetricsRef.current;
    metrics.frameCount++;
    
    // 每隔一段时间计算FPS
    if (timestamp - lastPerformanceCheckRef.current > PERFORMANCE_CHECK_INTERVAL) {
      const elapsed = timestamp - lastPerformanceCheckRef.current;
      metrics.fps = (metrics.frameCount / elapsed) * 1000;
      
      // 重置计数器
      metrics.frameCount = 0;
      lastPerformanceCheckRef.current = timestamp;
      
      // 根据性能调整粒子行为
      if (metrics.fps < 30 && !metrics.lowPerformanceMode) {
        // 如果FPS低于30，切换到低性能模式
        metrics.lowPerformanceMode = true;
        
        // 如果粒子数量超过最小值，减少粒子数量
        if (particlesRef.current.length > MIN_PARTICLES) {
          particlesRef.current = particlesRef.current.slice(0, MIN_PARTICLES);
        }
      } else if (metrics.fps > 50 && metrics.lowPerformanceMode) {
        // 如果FPS恢复，退出低性能模式
        metrics.lowPerformanceMode = false;
      }
    }
    
    return metrics.lowPerformanceMode;
  }, []);
  
  return {
    particlesRef,
    connectionPulsesRef,
    lastParticleCreationRef,
    performanceMetricsRef,
    lastPerformanceCheckRef,
    initParticles,
    checkPerformance,
    generateParticles,
    updateParticles,
    drawParticles,
    drawConnectionLines
  };
} 